using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.UI;

namespace BlockOS.Client
{
    public class CameraControl : MonoBehaviour
    {
        [SerializeField]
        private float lookSpeed = 4.5f;
        [SerializeField]
        private int moveSpeed = 10;
        public InputAction lookAction;
        public InputAction liftAction;
        public InputAction moveAction;


        private Vector3 yawPitch;
        private Vector2? moveVelocity;
        private Vector2? direction;
        private float? liftAxis;

        private Vector2 lookVelocity;

        // Start is called before the first frame update
        void Start()
        {
            liftAction.performed += ctx =>
            {
                liftAxis = ctx.ReadValue<float>();
            };
            liftAction.canceled += _ =>
            {
                liftAxis = null;
            };
            moveAction.performed += ctx => direction = ctx.ReadValue<Vector2>();
            moveAction.canceled += ctx => direction = null;
        }

        private void OnEnable()
        {
            //Cursor.lockState = CursorLockMode.Locked;
            //Cursor.visible = false;
            
            lookAction.Enable();
            liftAction.Enable();
            moveAction.Enable();
        }

        private void OnDisable()
        {
            //Cursor.lockState = CursorLockMode.None;
            //Cursor.visible = true;

            lookAction.Disable();
            liftAction.Disable();
            moveAction.Disable();
        }


        private void Update()
        {
            Look(lookAction.ReadValue<Vector2>());
            if (liftAxis != null) VerticalMove(liftAxis.Value);
            if (direction != null) HorizontalMove(direction.Value);
        }

        public void HorizontalMove(Vector2 direction)
        {
            var velocity = direction.x * transform.right + direction.y * transform.forward;
            transform.position += Time.deltaTime * moveSpeed * velocity;
        }

        public void VerticalMove(float axis)
        {
            
            transform.position += moveSpeed * axis * Time.deltaTime * Vector3.up;
        }



        public void Look(Vector2 delta)
        {
            yawPitch += lookSpeed * new Vector3(-delta.y, delta.x);
            yawPitch.x = Mathf.Clamp(yawPitch.x, -89, 89);

            transform.localRotation = Quaternion.Euler(yawPitch);

            GameClient.Instance.EventBus.AddEvent(new PlayerLookEvent(transform.forward));
        }

    }
}
